﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using FluentValidation.Results;
using Microsoft.Extensions.Configuration;
using PcProject.Application.Service.AutoMapper;
using PcProject.Domain.IRepository;
using PcProject.Domain.Models.Entities;
using PcProject.Domain.Models.Validation;

namespace PcProject.Infrastructure.Repository
{
    /// <summary>
    /// 商品实现类
    /// </summary>
    public class ProductRepository: DapperRepositoryBase<Product>, IProductRepository
    {
        //构造函数依赖注入
        public IConfiguration _configuration;
        //函数依赖注入
        public ProductRepository(IConfiguration configuration)
        {
            this._configuration = configuration;
            //连接字符串
            this.ConnStr = _configuration.GetConnectionString("PcMiniConnStr");
            SimpleCRUD.SetDialect(SimpleCRUD.Dialect.MySQL);
            Conn = new MySql.Data.MySqlClient.MySqlConnection(this.ConnStr);
        }


        /// <summary>
        /// 商品显示查询分页
        /// </summary>
        /// <param name="pname">查询参数</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="totalCount">总条数</param>
        /// <returns></returns>
        public List<Product> GetProductsAsync(string pname, int pageIndex, int pageSize, out int totalCount)
        {
            string sql = $"select * from Product a inner join ProductCategory b on a.ProType=b.CateId where 1=1 and IsDelete=1";
            //商品名称查询
            if (!string.IsNullOrEmpty(pname))
            {
                sql += $" and ProName like '%{pname}%'";
            }
            sql += $" limit @p1,@p2";
            //计算条数
            string sqlcount = $"select count(*) from Product";
            //总条数
            totalCount = Conn.ExecuteScalar<int>(sqlcount);
            return Conn.Query<Product>(sql, new { p1 = (pageIndex - 1) * pageSize, p2 = pageSize }).ToList();
        }

        /// <summary>
        /// 商品添加
        /// </summary>
        /// <param name="obj">参数</param>
        /// <returns></returns>
        public async Task<int> InserAsync(Product obj)
        {
            ValidationResult result = new ProductValidator().Validate(obj);
            if (!result.IsValid)
            {
                //遍历所有的失败对象
                foreach (var failure in result.Errors)
                {
                    throw new Exception("出现了一次异常");
                }
            }
            return (int)await Conn.InsertAsync(obj);
        }

        /// <summary>
        /// 商品删除
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<int> DeleAsync(int id)
        {
            string sql = $"delete from Product where ProId={id}";
            return await Conn.ExecuteAsync(sql);
        }

        /// <summary>
        /// 商品反填
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<Product> FillAsync(int id)
        {
            return await Conn.GetAsync<Product>(id);
        }

        /// <summary>
        /// 商品详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ProductDto FillsAsync(int id)
        {
            string sql = $"select * from Product a join Specification b on a.SpeId=b.SpeciId where ProId={id}";
            return Conn.Query<ProductDto>(sql).FirstOrDefault();
        }

        /// <summary>
        /// 加入浏览记录
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int AddBrowse(Browse obj)
        {
            return (int)Conn.Insert(obj);
        }

        /// <summary>
        /// 根据ID查找商品信息
        /// </summary>
        /// <returns></returns>
        public List<Product> Products(string b)
        {
            string sql = $"select * from Product where ProId in ({b})";
            return Conn.Query<Product>(sql).ToList();
        }

        /// <summary>
        /// 商品修改
        /// </summary>
        /// <param name="obj">参数</param>
        /// <returns></returns>
        public async Task<int> UptAsync(Product obj)
        {
            return await Conn.UpdateAsync(obj);
        }

        /// <summary>
        /// 修改价格
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int Upt(Product obj)
        {
            return Conn.Update(obj);
        }

        /// <summary>
        /// 加入回收站
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<int> RecycAsync(int id)
        {
            string sql = $"update Product set IsDelete=2 where ProId={id}";
            return await Conn.ExecuteAsync(sql);
        }

        /// <summary>
        /// 回收站显示分页
        /// </summary>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageSize">条数</param>
        /// <param name="totalCount">总条数</param>
        /// <returns></returns>
        public List<Product> GetRecycAsync(int pageIndex, int pageSize, out int totalCount)
        {
            string sql = $"select * from Product where IsDelete=2";
            sql += $" limit @p1,@p2";
            string sqlcount = $"select count(*) from Product";
            totalCount = Conn.ExecuteScalar<int>(sqlcount);
            return Conn.Query<Product>(sql, new { p1 = (pageIndex - 1) * pageSize, p2 = pageSize }).ToList();
        }

        /// <summary>
        /// 还原回收站
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<int> ResetAsync(int id)
        {
            string sql = $"update Product set IsDelete=1 where ProId={id}";
            return await Conn.ExecuteAsync(sql);
        }

        public async Task<Product> GetByIdAsyncs(int id)
        {
            return await Conn.GetAsync<Product>(id);
        }
        
    }
}
